import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';

// Import default avatar image
import defaultUserAvatar from '@/assets/images/default_user_avatar.jpg';

export const useAuthStore = defineStore('auth', () => {
  const currentUser = ref(null);
  const isAuthenticated = computed(() => !!currentUser.value);
  const userAvatar = computed(() => currentUser.value?.avatar || defaultUserAvatar);

  // 初始化时从 localStorage 加载用户信息
  const initAuth = () => {
    try {
      const savedUser = localStorage.getItem('currentUser');
      if (savedUser) {
        currentUser.value = JSON.parse(savedUser);
      }
    } catch (error) {
      console.error('Error initializing auth:', error);
      localStorage.removeItem('currentUser');
    }
  };

  // 登录
  const login = async (credentials) => {
    try {
      const users = JSON.parse(localStorage.getItem('users') || '[]');
      const user = users.find(u => u.username === credentials.username && u.password === credentials.password);
      
      if (user) {
        currentUser.value = {
          ...user,
          avatar: user.avatar || defaultUserAvatar,
          nickname: user.nickname || `用户${Math.floor(Math.random() * 1000)}`,
          bio: user.bio || '这个人很懒，什么都没写~',
          joinDate: user.joinDate || new Date().toISOString(),
          lastLogin: new Date().toISOString()
        };
        localStorage.setItem('currentUser', JSON.stringify(currentUser.value));
        return true;
      } else {
        throw new Error('用户名或密码错误');
      }
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  };

  // 注册
  const register = async (userData) => {
    try {
      // 从 localStorage 获取用户列表
      const users = JSON.parse(localStorage.getItem('users') || '[]');
      
      // 检查用户名是否已存在
      if (users.some(u => u.username === userData.username)) {
        throw new Error('用户名已存在');
      }

      // 创建新用户
      const newUser = {
        ...userData,
        avatar: defaultUserAvatar,
        nickname: `用户${Math.floor(Math.random() * 1000)}`,
        bio: '这个人很懒，什么都没写~',
        joinDate: new Date().toISOString(),
        lastLogin: new Date().toISOString(),
        favorites: [],
        history: [],
        settings: {
          theme: 'light',
          notifications: true
        }
      };

      // 保存到用户列表
      users.push(newUser);
      localStorage.setItem('users', JSON.stringify(users));

      return true;
    } catch (error) {
      throw error;
    }
  };

  // 登出
  const logout = () => {
    currentUser.value = null;
    localStorage.removeItem('currentUser');
  };

  // 更新用户头像
  const updateAvatar = async (avatarFile) => {
    if (!currentUser.value) {
      throw new Error('请先登录');
    }

    if (!avatarFile) {
      throw new Error('请选择要上传的头像');
    }

    try {
      // 创建一个 Promise 来处理文件读取
      const avatarUrl = await new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => resolve(e.target.result);
        reader.onerror = (error) => reject(new Error('文件读取失败'));
        reader.readAsDataURL(avatarFile);
      });

      // 更新当前用户的头像
      currentUser.value = {
        ...currentUser.value,
        avatar: avatarUrl
      };
      
      // 更新 localStorage 中的用户信息
      localStorage.setItem('currentUser', JSON.stringify(currentUser.value));

      // 更新用户列表中的头像
      try {
        const users = JSON.parse(localStorage.getItem('users') || '[]');
        const userIndex = users.findIndex(u => u.username === currentUser.value.username);
        if (userIndex !== -1) {
          users[userIndex] = {
            ...users[userIndex],
            avatar: avatarUrl
          };
          localStorage.setItem('users', JSON.stringify(users));
        }
      } catch (error) {
        console.error('Error updating user list:', error);
        // 不影响主流程，继续返回
      }

      return avatarUrl;
    } catch (error) {
      console.error('Avatar update error:', error);
      throw new Error(error.message || '头像更新失败');
    }
  };

  // 更新用户信息
  const updateUserInfo = async (userInfo) => {
    if (!currentUser.value) {
      throw new Error('请先登录');
    }

    try {
      currentUser.value = {
        ...currentUser.value,
        ...userInfo
      };
      localStorage.setItem('currentUser', JSON.stringify(currentUser.value));
      
      // 同时更新用户列表中的信息
      const users = JSON.parse(localStorage.getItem('users') || '[]');
      const userIndex = users.findIndex(u => u.username === currentUser.value.username);
      if (userIndex !== -1) {
        users[userIndex] = {
          ...users[userIndex],
          ...userInfo
        };
        localStorage.setItem('users', JSON.stringify(users));
      }
      return true;
    } catch (error) {
      console.error('User info update error:', error);
      throw new Error('用户信息更新失败');
    }
  };

  // 初始化
  initAuth();

  return {
    currentUser,
    isAuthenticated,
    userAvatar,
    login,
    register,
    logout,
    updateUserInfo,
    updateAvatar
  };
});